<template>
  <view class="page pageBg-color">

    <!-- 自定义头部导航栏 -->
    <com-nav-bar title="推荐"></com-nav-bar>

    <scroll-view 
      scroll-y 
      refresher-enabled 
      @refresherrefresh="onRefresh" 
      :refresher-triggered="isLoading"
      refresher-background="#fff" 
      class="scroll-view"
      >

      <!-- 轮播图 -->
      <view class="banner">
        <com-banner :dataList="bannerList" :isEmpty="Banner_isEmpty"></com-banner>
      </view>

      <!-- 公告 -->
      <view class="notice">
        <com-notice :dataList="noticeList" :isEmpty="Notice_isEmpty"></com-notice>
      </view>

      <!-- 功能卡片 -->
      <view class="feature-card">

        <view v-for="item in grids" :key="item.id" :data-item="item" @click="onGridSelect"
          :style="{ background: item.backgroundStyle }" class="card-item">
          <view :style="{ backgroundColor: item.backgroundColor }" class="left">
            <view class="title">
              <text>{{ item.title }}</text>
            </view>
            <view class="content">
              <text>{{ item.content }}</text>
            </view>
            <uni-icons custom-prefix="iconfont" :color="item.color" type="icon-youjiantou" size="20"></uni-icons>
          </view>
          <view class="right">
            <view class="top"></view>
            <view :style="{ backgroundColor: item.backgroundColor }" class="bottom"></view>
          </view>
          <view class="bg-image">
            <image class="image" :src="item.imageUrl" mode="aspectFill" />
          </view>
        </view>

      </view>

      <!-- 每日推荐 -->
      <view class="recommend">
        <com-title>
          <template #title>每日推荐</template>
          <template #custom>
            <view class="date">
              <uni-icons type="calendar" color="#ffab96" size="28"></uni-icons>
              <!-- #ifdef MP-WEIXIN -->
              <uni-dateformat :date="time" format="dd号"></uni-dateformat>
              <!-- #endif -->
              <!-- #ifdef H5 -->
              <uni-dateformat :date="time"></uni-dateformat>
              <!-- #endif -->
            </view>
          </template>
        </com-title>

        <com-empty v-if="Recommend_isEmpty" />
        <scroll-view v-else scroll-x class="scroll-view">
          <view @click="goPreview(item._id)" v-for="item in recommendList" :key="item._id" class="item">
            <image :src="item.smallPicurl" lazy-load mode="aspectFill" class="image" />
          </view>
        </scroll-view>
      </view>

      <!-- 分类精选 -->
      <view class="selected">
        <com-title>
          <template #title>分类精选</template>
          <template #custom>
            <view @click="goMore('Type')" class="head-more">
              <text>More+</text>
            </view>
          </template>
        </com-title>

        <view class="content">
          <list-type :dataList="classifyList" :isEmpty="Classify_isEmpty" :isHaveMore="true" :isHide="true"></list-type>
        </view>
      </view>

      <!-- 专题推荐 -->
      <view class="special-feature">
        <com-title>
          <template #title>专题推荐</template>
          <template #custom>
            <view @click="goMore('Subject')" class="head-more">
              <text>More+</text>
            </view>
          </template>
        </com-title>

        <com-empty v-if="Subject_isEmpty" />
        <scroll-view v-else scroll-x class="scroll-view">
          <view @click="goSubject(item._id)" v-for="item in subjectList" :key="item._id" class="item">
            <view class="card">

              <view class="pic-list">
                <view class="group">
                  <view v-for="value in item.picList" :key="value._id" class="pic">
                    <image :src="value.smallPicurl" lazy-load mode="aspectFill" class="image" />
                  </view>
                </view>
              </view>

              <view class="footer">
                <view class="title">
                  <text>{{ item.theme }}</text>
                </view>
                <view class="content">
                  <view class="like-num">
                    <text>{{ item.view_count }}人喜欢</text>
                  </view>
                  <view class="image-num">
                    <uni-icons type="image" color="#ccc" size="22"></uni-icons>
                    <text>{{ item.size }}P</text>
                  </view>
                </view>
              </view>

            </view>
            <view class="line1"></view>
            <view class="line2"></view>
          </view>
        </scroll-view>

      </view>

    </scroll-view>

  </view>
</template>


<script setup lang="ts">
import { ref } from 'vue';
import { isEmpty } from "@/utils/utils";
import { onLoad, onReady, onUnload, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { API } from "@/services/api";
import { useClassListStore } from "@/store";
const ClassListStore = useClassListStore();

const time = ref(Date.now()); // 每日推荐的时间显示

// 监听页面加载 de 生命周期
onLoad(() => {
  onRefresh();
});

// 监听页面初次渲染完成 de 生命周期
onReady(() => {
  // #ifdef H5
  startTime();
  // #endif
});

// 监听页面卸载 de 生命周期
onUnload(() => {
  // #ifdef H5
  clearInterval(timer);
  // #endif
});

// 分享给好友
onShareAppMessage(() => {
  return {
    title: "我的第一个uniApp",
    path: "/pages/index/index"
  }
});

// 转发到朋友圈（目前还不知道是什么原因没有生效）
onShareTimeline(() => {
  return {
    title: "我的第一个uniApp"
  }
})

// 自定义下拉刷新函数
const isLoading = ref(false); // 加载状态
const onRefresh = async () => {
  isLoading.value = true; // 开始加载

  // 清空所有数据
  bannerList.value = [];
  noticeList.value = [];
  recommendList.value = [];
  ClassListStore.clearList();
  classifyList.value = [];
  subjectList.value = [];

  try {
    // 使用 Promise.allSettled 等待所有请求完成（无论成功与否）
    await Promise.allSettled([
      getBanner(),
      getNotice(),
      getRecommend(),
      getClassify(),
      getSubject()
    ]);
  } finally {
    // 无论成功或失败，最终都关闭加载状态
    isLoading.value = false;
  }
};

// 获取轮播图数据
const bannerList: any = ref([]);
const Banner_isEmpty = ref(true);
const getBanner = () => {
  API.homeBanner()
    .then((res: any) => {
      bannerList.value = res.data;
      Banner_isEmpty.value = bannerList.value.length <= 0;
    })
    .catch(() => {
      Banner_isEmpty.value = true;
    })
};

// 获取公告数据
const noticeList: any = ref([]);
const Notice_isEmpty = ref(true);
const getNotice = () => {
  API.wallNewsList(true)
    .then((res: any) => {
      noticeList.value = res.data;
      Notice_isEmpty.value = noticeList.value.length <= 0;
    })
    .catch(() => {
      Notice_isEmpty.value = true;
    })
};

// 获取每日推荐壁纸
const recommendList: any = ref([]);
const Recommend_isEmpty = ref(true);
const getRecommend = () => {
  API.randomWall()
    .then((res: any) => {
      recommendList.value = res.data;
      Recommend_isEmpty.value = recommendList.value.length <= 0;
      ClassListStore.setList(recommendList.value);
    })
    .catch(() => {
      Recommend_isEmpty.value = true;
    })
};

// 获取分类精选
const classifyList: any = ref([]);
const Classify_isEmpty = ref(true);
const getClassify = () => {
  API.classify(undefined, undefined, true)
    .then((res: any) => {
      classifyList.value = res.data;
      Classify_isEmpty.value = classifyList.value.length <= 0;
    })
    .catch((res: any) => {
      Classify_isEmpty.value = true;
    })
};

// 获取专题列表
const subjectList: any = ref([]);
const Subject_isEmpty = ref(true);
const getSubject = () => {
  API.subjectList(1, 6)
    .then((res: any) => {
      subjectList.value = res.data;
      Subject_isEmpty.value = subjectList.value.length <= 0;
    })
    .catch((res: any) => {
      Subject_isEmpty.value = true;
    })
};

// 每秒更新一次时间
let timer: number; // 每秒更新定时器
const startTime = () => {
  timer = setInterval(() => {
    time.value = Date.now();
  }, 1000);
};

// 功能卡片数组
const grids = ref([ //
  {
    "id": "1",
    "title": "萌宠集合",
    "content": "可爱的猫猫狗狗",
    "path": "/pages/pkgC/cutePet/index",
    "imageUrl": "/static/images/image_pinkBear.png",
    "color": "#2DB68D",
    "backgroundColor": "#C5EFDB",
    "backgroundStyle": "radial-gradient(50rpx 50rpx at 65% 30%, #C5EFDB, transparent)",
    "h5": "",
    "appId": "",
    "needLogin": false,
  }, {
    "id": "2",
    "title": "淘宝买家秀",
    "content": "查看买家晒的商品照片",
    "path": "/pages/pkgC/taoShow/index",
    // "path": "/pages/pkgD/demo/index",
    "imageUrl": "/static/images/image_astronaut.png",
    "color": "#FC8D69",
    "backgroundColor": "#F5E6DC",
    "backgroundStyle": "radial-gradient(50rpx 50rpx at 65% 30%, #F5E6DC, transparent)",
    "h5": "",
    "appId": "",
    "needLogin": false,
  },
]);

// 点击 功能卡片数组 de 跳转
const onGridSelect = (e: any) => {
  let item = e.currentTarget.dataset.item;
  // console.log("~~~", item);

  // if (item.needLogin) {
  // 	console.log("~~~需要登录");
  // 	return;
  // }

  // 跳转小程序
  // if (!isEmpty(item.appId)) {
  // 	console.log("~~~跳转小程序");
  // 	uni.navigateToMiniProgram({
  // 		appId: item.appId,
  // 		path: item.path ?? '' // 打开的页面路径，如果为空则打开首页
  // 	})
  // 	return;
  // }

  // 跳转内部页面
  if (!isEmpty(item.path)) {
    uni.navigateTo({
      url: `${item.path}?name=demo&sex=1`
    })
  }

};

// 点击 More+ de 跳转
const goMore = (value: string) => {
  if (value === "Type") {
    uni.switchTab({
      url: "/pages/type/index"
    });
  }

  if (value === "Subject") {
    uni.navigateTo({
      url: `/pages/pkgB/subjectIndex/index`
    })
  }
};

// 点击 每日推荐 de 跳转
const goPreview = (id: string) => {
  ClassListStore.setList(recommendList.value);
  uni.navigateTo({
    url: `/pages/pkgB/typePreview/index?id=${id}`
  })
};

// 点击 专题推荐 de 跳转
const goSubject = (id: string) => {
  uni.navigateTo({
    url: `/pages/pkgB/subjectList/index?id=${id}`
  })
};
</script>


<style scoped lang="scss">
@use "style.scss";
</style>
